import React, { Component } from 'react';
import * as RecordAPI from '../api/RecordAPI'

class Record extends Component {
  constructor() {
    super()
    this.state = {
      edit: false
    }
  }

  handleToggle = () => {
    this.setState({
      edit: !this.state.edit
    })
  }

  handleEdit = (event) => {
    event.preventDefault();
    let record = {
      date: this.refs.date.value,
      title: this.refs.title.value,
      amount: this.refs.amount.value
    }
    RecordAPI.update(this.props.record.id, record).then(res => {
      console.log(res)
      this.props.handleEditRecord(this.props.record, res.data)
      this.handleToggle()
    }).catch(error => {
      console.log(error)
    })
    // console.log(record);
  }

  handleDelete = (event) => {
    event.preventDefault()
    RecordAPI.remove(this.props.record.id).then(res => {
      this.props.handleDeleteRecord(this.props.record)
    }).catch(error => {
      console.log(error);
    })
  }

  recordRow() {
    return (
      <tr>
        <td>{this.props.record.id}</td>
        <td>{this.props.record.date}</td>
        <td>{this.props.record.title}</td>
        <td>{this.props.record.amount}</td>
        <td>
          <button className="btn btn-info mr-1" onClick={this.handleToggle}>Edit</button>
          <button className="btn btn-danger" onClick={this.handleDelete} >Delete</button>
        </td>
      </tr>
    )
  }
  recordForm() {
    return (
      <tr>
        <td>{this.props.record.id}</td>
        <td><input type="text" className="form-control" defaultValue={this.props.record.date} ref="date" /></td>
        <td><input type="text" className="form-control" defaultValue={this.props.record.title} ref="title" /></td>
        <td><input type="text" className="form-control" defaultValue={this.props.record.amount} ref="amount" /></td>
        <td>
          <button className="btn btn-info mr-1" onClick={this.handleEdit}>Update</button>
          <button className="btn btn-danger " onClick={this.handleToggle}>Cancel</button>
        </td>
      </tr>
    )
  }
  render() {
    if (!this.state.edit){
      return this.recordRow()
    } else {
      return this.recordForm()
    }
  }
}

export default Record;
